package ru.spb.osll.myfit.client.view;

import ru.spb.osll.myfit.client.dialog.ErrorDialog;
import ru.spb.osll.myfit.client.manager.PageElementManager;
import ru.spb.osll.myfit.client.service.FitService;
import ru.spb.osll.myfit.client.service.FitServiceAsync;
import ru.spb.osll.myfit.client.widget.GWTWidgetFactory;
import ru.spb.osll.myfit.client.widget.PageWidget;
import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.PageElement;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class MyFitViewController implements IViewController {

  private ErrorDialog m_errorDialog = new ErrorDialog();
  /**
   * Create a remote service proxy to talk to the server-side Fit service.
   */
  private final FitServiceAsync m_fitService = GWT.create(FitService.class);

  public MyFitViewController() {

  }

  @Override
  public IView getView(String address) {
    PageWidget pageWidget = new PageWidget(new GWTWidgetFactory());
    pageWidget.setPagePath(address);
    PageElementManager pageElementManager = new PageElementManager();
    pageWidget.addPageEventListener(pageElementManager);
    MyFitView view = new MyFitView(address, pageWidget, m_fitService);
    loadPage(address, view);
    return view;
  }

  private void loadPage(final String address, final MyFitView view) {

    m_fitService.loadPage(address, new AsyncCallback<Page>() {

      public void onFailure(Throwable caught) {
        m_errorDialog.center();
      }

      public void onSuccess(Page page) {
        if (page != null) {
          for (PageElement element : page.getElements()) {
            view.addPageElementWidget(element);
          }
        }
      }
    });
  }
}
